extends CharacterBody2D


const SPEED = 100.0
const JUMP_VELOCITY = -400.0
const WIN_SIZE = Vector2(380, 490)	# 窗口大小
@onready var body_idle = $BodyIdle
@onready var body_walk = $BodyWalk
@onready var body_fly = $BodyFly

@onready var animation_tree = $AnimationTree


var playback 	# 状态基
var direction:Vector2	# 方向
var screen:Vector2	# 屏幕大小
var dragging := false	# 鼠标拖拽
var win_pos:Vector2	 # 窗口位置
var mouse_pos:Vector2	# 鼠标位置
var mouse_in_pos:Vector2	# 鼠标进入位置
var vel:Vector2	# 角色速度向量

var round_time:float = 3.0	# 定时器，设定时间为3s
var time_count:float = 0	# 计时器

func _ready():
	playback = animation_tree.get("parameters/playback")
	screen = DisplayServer.screen_get_size()	# 初始化屏幕
	get_tree().get_root().size = WIN_SIZE
	
func _input(event):		# 鼠标拖拽、输入
	if event is InputEventMouseButton:	# 如果鼠标是点击事件的话
		if event.button_index ==MOUSE_BUTTON_LEFT and event.pressed:
			dragging = true
			mouse_in_pos = get_viewport().get_mouse_position()
		else:
			dragging = false	# 放开拖拽
			
	if event is InputEventMouseMotion and dragging:	 # 如果鼠标是拖拽事件的话
		mouse_pos = get_viewport().get_mouse_position()
		get_tree().get_root().position = Vector2(get_tree().get_root().position) + mouse_pos - mouse_in_pos
		
	if event is InputEventKey and event.is_action_pressed("exit"):	# esc退出
		get_tree().quit()
	
var auto_direction:Vector2
func _physics_process(delta):
	vel = Vector2.ZERO	# 键盘结束后复位
	direction = Vector2(Input.get_axis("ui_left", "ui_right"),Input.get_axis("ui_up", "ui_down"))
	if direction != Vector2.ZERO:
		vel = direction * delta * SPEED
		time_count = round_time	#如果手动输入，计算时间
	else :	# 如果没有输入，小鱼自动行动
		time_count -=delta
		if time_count < 0:	# 如果时间到了，计时器重置
			time_count = round_time
			auto_direction = select_new_direction()	# 一个新的方向
		vel = auto_direction * SPEED *delta
	
	# 获取方向后反转
	if vel.x > 0 and body_walk.flip_h: # 如果获得方向的值大于0且方向未翻转
		body_walk.flip_h = false	# 如果已经翻转，让小鱼转回来
		body_idle.flip_h = false
	elif vel.x < 0 and !body_walk.flip_h: # 这个值如果小于0，就让它再转回来
		body_walk.flip_h = true
		body_idle.flip_h = true
					

	win_pos = Vector2(get_tree().get_root().position) + vel
	
	# 限制不能跑出屏幕
	win_pos.x = clamp(win_pos.x,0,screen.x - WIN_SIZE.x)
	win_pos.y = clamp(win_pos.y,0,screen.y - WIN_SIZE.y)	# 减去窗口尺寸防止从下方跳出屏幕外
	get_tree().get_root().position = win_pos
	
	pick_new_state()

var walk:float = false	# 走动判断
func select_new_direction()->Vector2:	# 选择一个新的方向
	# 判断自动求法
	walk = !walk
	if walk:
		return Vector2(
			randf_range(-1,1),
			randf_range(-1,1)
		)
	else:	# 如果不是，随机返回一个让小鱼原地站立的方向
		return Vector2.ZERO
		
		
func pick_new_state():
	# 状态机
	body_walk.visible = false
	body_idle.visible = false
	body_fly.visible = false
	
	if dragging:
		playback.travel("fly")
		body_fly.visible = true;
		print("fly")
	elif(vel != Vector2.ZERO):
		playback.travel("walk")
		body_walk.visible = true;
		print("walk")
	else:
		playback.travel("idle")
		body_idle.visible = true;
		print("idle")
